import {NbGoStep} from '../NbGoStep.js';
import {normalizeConfigValue, parseBoolean} from '../GoUtils.js';
import {StrUtil} from '../../../utils/StrUtil.js';

function buildPlanPayload(projectOpsFile, flowId, flowType) {
    const title = normalizeConfigValue(projectOpsFile.read('flow.plan.title'));
    const version = normalizeConfigValue(projectOpsFile.read('flow.plan.version'));
    const pipelineId = normalizeConfigValue(projectOpsFile.read('flow.plan.pipeline_id'));
    const vopsBu = normalizeConfigValue(projectOpsFile.read('flow.plan.vops_bu'));
    const vopsZone = normalizeConfigValue(projectOpsFile.read('flow.plan.vops_zone'));
    const deployTime = normalizeConfigValue(projectOpsFile.read('flow.plan.plan_deploy_time'));
    const planType = normalizeConfigValue(projectOpsFile.read('flow.plan.type')) || 'version';
    const onlyCurrentRaw = projectOpsFile.read('flow.plan.only_current');
    if (StrUtil.isNull(title) || StrUtil.isNull(version) || StrUtil.isNull(pipelineId) || StrUtil.isNull(vopsBu) || StrUtil.isNull(vopsZone)) {
        throw new Error('请在 ops.conf 中补齐 flow.plan.title/version/pipeline_id/vops_bu/vops_zone 配置');
    }
    const onlyCurrent = parseBoolean(onlyCurrentRaw, true);
    return {
        type: planType,
        only_current: onlyCurrent,
        flow_id: flowId,
        flow_type: flowType,
        title,
        plan_deploy_time: deployTime,
        vops_bu: vopsBu,
        vops_zone: vopsZone,
        version,
        pipeline_id: pipelineId
    };
}

export class CreatePlanStep extends NbGoStep {
    constructor() {
        super({
            key: 'createPlan',
            name: '创建发布计划',
            description: '根据配置创建发布计划'
        });
    }

    async shouldSkip(context, state) {
        if (state?.status === 'completed' && state?.metadata?.planId) {
            return {
                skip: true,
                reason: `已在状态文件中记录发布计划 ID=${state.metadata.planId}`,
                metadata: state.metadata
            };
        }
        return {skip: false};
    }

    async execute(context) {
        const {pipeline, opsClient, projectOpsFile} = context;
        const {flowId, flowType} = pipeline.getFlowIdentity();
        const payload = buildPlanPayload(projectOpsFile, flowId, flowType);
        const res = await opsClient.createFlowPlan(payload);
        const planId = typeof res === 'object' && res !== null ? (res.id ?? res.plan_id ?? res.data) : res;
        if (!planId) {
            throw new Error('发布计划创建响应缺少 ID');
        }
        const planIdStr = String(planId).trim();
        await opsClient.getPlanRelease(planIdStr);
        context.cache.planId = planIdStr;
        return {
            planId: planIdStr,
            payload,
            finishedAt: new Date().toISOString()
        };
    }
}
